package com.rickpan.controller;

import com.rickpan.dto.common.ApiResponse;
import com.rickpan.dto.chat.*;
import com.rickpan.service.ChatSessionService;
import com.rickpan.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * AI聊天会话控制器
 */
@RestController
@RequestMapping("/api/chat/sessions")
public class ChatSessionController {

    @Autowired
    private ChatSessionService chatSessionService;

    /**
     * 创建新会话
     */
    @PostMapping
    public ResponseEntity<ApiResponse<ChatSessionDTO>> createSession(@Valid @RequestBody CreateSessionRequest request) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            ChatSessionDTO session = chatSessionService.createSession(userId, request);
            return ResponseEntity.ok(ApiResponse.success(session));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("创建会话失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户的会话列表
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<ChatSessionDTO>>> getSessions(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            List<ChatSessionDTO> sessions = chatSessionService.getUserSessions(userId, page, size);
            return ResponseEntity.ok(ApiResponse.success(sessions));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取会话列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取会话详情（包含消息）
     */
    @GetMapping("/{sessionId}")
    public ResponseEntity<ApiResponse<ChatSessionDetailDTO>> getSessionDetail(@PathVariable Long sessionId) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            ChatSessionDetailDTO sessionDetail = chatSessionService.getSessionDetail(userId, sessionId);
            return ResponseEntity.ok(ApiResponse.success(sessionDetail));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取会话详情失败: " + e.getMessage()));
        }
    }

    /**
     * 更新会话标题
     */
    @PutMapping("/{sessionId}/title")
    public ResponseEntity<ApiResponse<Void>> updateSessionTitle(
            @PathVariable Long sessionId,
            @Valid @RequestBody UpdateSessionTitleRequest request) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            chatSessionService.updateSessionTitle(userId, sessionId, request.getTitle());
            return ResponseEntity.ok(ApiResponse.success(null));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("更新会话标题失败: " + e.getMessage()));
        }
    }

    /**
     * 删除会话
     */
    @DeleteMapping("/{sessionId}")
    public ResponseEntity<ApiResponse<Void>> deleteSession(@PathVariable Long sessionId) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            chatSessionService.deleteSession(userId, sessionId);
            return ResponseEntity.ok(ApiResponse.success(null));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("删除会话失败: " + e.getMessage()));
        }
    }

    /**
     * 保存消息到会话
     */
    @PostMapping("/{sessionId}/messages")
    public ResponseEntity<ApiResponse<ChatMessageDTO>> saveMessage(
            @PathVariable Long sessionId,
            @Valid @RequestBody SaveMessageRequest request) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            ChatMessageDTO message = chatSessionService.saveMessage(userId, sessionId, request);
            return ResponseEntity.ok(ApiResponse.success(message));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("保存消息失败: " + e.getMessage()));
        }
    }

    /**
     * 清空会话的所有消息
     */
    @DeleteMapping("/{sessionId}/messages")
    public ResponseEntity<ApiResponse<Void>> clearSessionMessages(@PathVariable Long sessionId) {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            chatSessionService.clearSessionMessages(userId, sessionId);
            return ResponseEntity.ok(ApiResponse.success(null));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("清空会话消息失败: " + e.getMessage()));
        }
    }
}
